<template>
  <div class="home">
    <van-action-sheet
      v-model="aSelectItemShow"
      :actions="aSelectItemActions"
      cancel-text="取消"
      close-on-click-action
      @select="upload"
    />
    <van-nav-bar title="个人设置" left-arrow @click-left="onClickLeft" />
    <div class="home-content">
      <!-- <div > -->
      <div class="home-content-cell avtor" @click="aSelectItemShow = true">
        <div>头像</div>
        <div style="width: 5rem; height: 5rem; border-radius: 5rem">
          <van-image
            round
            width="5rem"
            height="5rem"
            :src="avtorData"
            error-icon="user-circle-o"
          />
        </div>
      </div>
      <van-cell
        class="home-content-cell"
        title="昵称"
        size="large"
        is-link
        :value="nickName"
        @click="toPage('updateUserName')"
      />
      <!-- </div> -->
    </div>
  </div>
</template>

<script>
import { Toast } from "vant";
import mqtt from "mqtt";
//import { Toast } from 'vant';
var client;
const options = {
  connectTimeout: 40000,
  clean: true,
};
client = mqtt.connect("ws://121.5.58.100:8083/mqtt", options);

export default {
  name: "center",
  data: function () {
    return {
      nickShow: true,
      file: [],
      Size: 100,
      showFill: false,
      showPosition: false,
      fillData: "",
      stepShow: false,
      BackgroundCSS: "",
      position: "",
      fill: "",
      paramsRes: "",
      aSelectItemShow: false,
      aSelectItemActions: [{ name: "拍照" }, { name: "从相册选择" }],
    };
  },
  created() {
    // try {
    //   //  var res = "http://121.5.58.100/avatar/" +
    //   //   localStorage.getItem("setUserID") +
    //   //   "_avatar.jpg?tempid=" +
    //   //   Math.random()
    //   this.avtorData = require("https://profile.csdnimg.cn/6/5/7/1_weixin_48286936");
    // } catch (err) {
    //   this.avtorData = require("@/assets/img/default_avatar.png");
    // }
    // this.avtorData=this.$store.state.userAvatar;
    // console.log(this.avtorData)
    // this.avtorData =
    //   "http://121.5.58.100/avatar/" +
    //   localStorage.getItem("setUserID") +
    //   "_avatar.jpg?tempid=" +
    //   Math.random();
  },
  computed: {
    avtorData: {
      get() {
        return this.$store.state.userAvatar;
      },
      set(v) {
        // 使用vuex中的mutations中定义好的方法来改变
        this.$store.commit("saveUserAvatar", v);
      },
    },
    nickName: {
      get() {
        return this.$store.state.nickName;
      },
      set(v) {
        // 使用vuex中的mutations中定义好的方法来改变
        this.$store.commit("saveNickName", v);
      },
    },
  },
  methods: {
    toPage(page) {
      this.$router.push({
        name: page,
        params: {
          routerType: "push",
        },
      });
    },
    defaultImg() {
      console.log("error");
    },
    handleLoad(e) {
      console.log(e, "sds");
    },
    onASelect(res) {
      this.upload(res.name);
      // console.log(res)
    },
    upload(item) {
      this.aSelectItemShow = false;
      var self = this;

      if (item.name == "拍照") {
        navigator.camera.getPicture(
          function success(imageURI) {
            plugins.crop(
              function success(url) {
                url = url.split("?");
                self.upfile(url[0]);
              },
              function fail(err) {
                console.log(err);
              },
              imageURI,
              { quality: 80 }
            );
          },
          function fail(message) {
            Toast({
              message: "未指定图片",
              position: "bottom",
            });
          },
          {
            //拍照
            destinationType: Camera.DestinationType.FILE_URI,
          }
        );
      } else if (item.name == "从相册选择") {
        navigator.camera.getPicture(
          function success(imageURI) {
            plugins.crop(
              function success(url) {
                url = url.split("?");
                self.upfile(url[0]);
              },
              function fail(err) {
                navigator.notification.alert(
                  "裁剪失败，原因：" + err,
                  null,
                  "警告"
                );
                console.log(err);
              },
              imageURI,
              { quality: 80 }
            );
          },
          function fail(message) {
            Toast({
              message: "未指定图片",
              position: "bottom",
            });
          },
          {
            //相册选图
            mediaType: Camera.MediaType.PICTURE,
            sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
          }
        );
      }
    },
    //上传图片
    upfile(fileURL) {
      var self = this;
      var uri = encodeURI("http://121.5.58.100:8000/userRecord/pic/upload"); //服务器接收地址

      var options = new FileUploadOptions();
      options.fileKey = "file"; //表单元素的名称。默认为file
      options.fileName = localStorage.getItem("setUserID") + "_avatar.jpg"; //在服务器上保存文件时要使用的文件名。默认为image.jpg
      options.mimeType = "image/jpeg"; //要上传的数据的MIME类型。默认为image/jpeg。
      options.headers = { headerParam: "headerValue" };
      var ft = new FileTransfer();
      // 上传进度
      // ft.onprogress = function(progressEvent) {
      //     if (progressEvent.lengthComputable) {
      //         loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total);
      //     } else {
      //         loadingStatus.increment();
      //     }
      // };

      ft.upload(
        fileURL,
        uri,
        function win(r) {
          Toast({
            message: "头像上传成功",
            position: "bottom",
          });
          self.avtorData =
            "http://121.5.58.100/avatar/" +
            localStorage.getItem("setUserID") +
            "_avatar.jpg?tempid=" +
            Math.random();
          // self.$store.commit(
          //   "saveUserAvatar",
          //   localStorage.getItem("setUserID")
          // );
        },
        function fail(error) {
          Toast({
            message: "头像上传失败" + error,
            position: "bottom",
          });
        },
        options
      );
    },
    afterRead(file) {
      console.log(file);
      this.avtorData = file.content;
    },
    submit() {
      if (!this.fillData) {
        Toast.fail("提交信息不能为空");
      } else {
        this.$http
          .get("http://121.5.58.100:8000/queryOTA", {
            params: {
              userAgent: this.fillData + "     Agent:" + navigator.userAgent,
              version: this.$version,
            },
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
            },
          })
          .then((result) => {
            this.fillData = "";
            Toast.success("提交成功");
          });
      }
    },
    onClickLeft() {
      this.$router.go(-1);
    },
  },
};
</script>

<style lang="scss" scoped>
.v-enter,
.v-leave-to {
  opacity: 0;
  transform: translateX(100px);
}

.v-enter-active,
.v-leave-to {
  transition: all 0.6s ease;
}

/* v-move 和 v-leave-to 配合使用，能够实现列表后续的元素，逐渐飘上来的效果 */
.v-move {
  transition: all 0.6s ease;
}

.v-leave-to {
  position: absolute;
}
.home {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: auto;
  display: flex;
  flex-flow: column;
  &-content {
    margin: 20px;
    border-radius: 20px;
    z-index: 5;
    &-cell {
      margin: 0 0 10px 0;
      width: auto;
      border-radius: 10px;
      background-color: rgba(255, 255, 255, 0.85);
      backdrop-filter: blur(20px) saturate(180%);
    }
  }
}
.custom-button {
  width: auto;
  padding: 5px 10px;
  color: #fff;
  font-size: 4vw;
  line-height: 5vw;
  text-align: center;
  background-color: #0aadee;
  border-radius: 20px;
}
// .van-cell {
//   margin: 0 0 10px 0;
//   width: auto;
//   border-radius: 10px;
//   box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
// }
.changebg-bottom {
  position: fixed;
  display: flex;
  flex-direction: row;
  bottom: 50px;
  width: calc(100% - 40px);
}
.van-button {
  margin: 10px;
}
.avtor {
  padding: 12px 16px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
</style>
